<template>
    <div class="map-container-wrapper">
        <div id="map-container"></div>
        <el-row>
            <el-cascader
            v-model="value"
            :options="options"
            :props="{ expandTrigger: 'hover' }"
            @change="handleChange"></el-cascader>
        </el-row>
        <el-row>
            <el-input v-model="inputParking" placeholder="请输入车位编号" style="width: 200px;">
                <template slot="prepend">车位</template>
            </el-input>
            <el-button type="primary" @click="searchByParking">查询</el-button>
        </el-row>
        <el-row>
            <el-input v-model="inputCar" placeholder="请输入车牌号" style="width: 200px;"></el-input>
            <el-button type="primary" @click="searchByCar">查询</el-button>
        </el-row>

        <!-- 状态标识元素 -->
        <div class="status-legend">
            <div v-for="(status, index) in statusname" :key="index" class="status-item">
                <span class="status-color" :style="{backgroundColor: statusColors[index]}"></span>
                <span class="status-text">{{ status }}</span>
            </div>
        </div>
        <el-dialog title="车位详情" :visible.sync="dialogParkVisible" center width="250px">
            <el-row type="flex" justify="center">
                {{ "车位ID：" + parkSpaceData.id }}
            </el-row>
            <el-row type="flex" justify="center">
                {{ "车位名称：" + parkSpaceData.name }}
            </el-row>
            <el-row type="flex" justify="center">
                {{ "车位状态：" + parkSpaceData.status }}
            </el-row>
            <el-row type="flex" justify="center">
                {{ "车牌号：" + parkSpaceData.licensePlate }}
            </el-row>
            <el-row type="flex" justify="center">
                {{ "车主姓名：" + parkSpaceData.userName }}
            </el-row>
            <el-row type="flex" justify="center">
                {{ "车主电话：" + parkSpaceData.phone }}
            </el-row>
        </el-dialog>
    </div>
</template>
<script>
import MapApplication from '@/esmap/MapApplication.js'; 
import { listSpaceByArea, querySpaceByCar } from "@/api/parking/space";
import { listArea } from "@/api/parking/area";
export default {
    name: 'MapContainer',
    data() {
        return {
            building:"",
            locateMarkLayer:null,
            inputParking:"",
            inputCar:"",
            value: [1,1],
            options: [],
            dialogParkVisible:false,
            mapID: '10005',
            parkSpaceData:{
                id:"",
                name:"",
                status:"",
                licensePlate:"",
                userName:"",
                phone:""
            },
            statusname: ["空闲","已预订","已占用","维护中","包月车位"],
            // 为每种状态定义颜色
            statusColors: [
                "#00FF00", // 空闲 - 绿色
                "#0000FF", // 已预订 - 蓝色
                "#FF0000", // 已占用 - 红色
                "#808080", // 维护中 - 灰色
                "#800080"  // 包月车位 - 紫色
            ]
        };
    },
    methods: {
        searchByCar(){
            if (this.inputCar === "") {
                this.$message({
                    message:"不支持空查询",
                    type:"error",
                    duration:1000,
                }) 
            } else {
                querySpaceByCar({
                    scLicensePlate:this.inputCar
                }).then(response => {
                    if (response.rows.length === 0) {
                        this.$message({
                            message:"查不到",
                            type:"error",
                            duration:1000,
                        }) 
                    } else {
                        this.esmapSearch(response.rows[0].scSpaceName.replace(/车位/g, ""))
                    }
                });
            }

        },
        searchByParking(){
            if (this.inputParking === "") {
                this.$message({
                    message:"不支持空查询",
                    type:"error",
                    duration:1000,
                }) 
            } else {
                this.esmapSearch(this.inputParking)
            }
            
        },
        esmapSearch(parkingName) {
            esmap.ESMapUtil.search(MapApplication.map,[1,2], {
                nodeType: esmap.ESNodeType.MODEL,
                keyword: "车位" + parkingName
            }, e => {
                console.log(e);
                if (e.length > 0) {
                    MapApplication.map.moveTo({
                        x: e[0].mapCoord.x,
                        y: e[0].mapCoord.y,
                        fnum: e[0].FloorNum,
                        time: 0.5
                    });
                    this.building = MapApplication.map.getBuilding();
                    if (e[0].nodeType == 5) {
                        var coordx = e[0].mapCoord.x,
                            coordy = e[0].mapCoord.y;
                        this.addMarker(coordx, coordy, e[0].FloorNum);
                    }
                    this.building.findRoomById({
                        id:e[0].ID,
                        fnum:e[0].FloorNum,
                        isSelect:true
                    })
                } else {
                    this.$message({
                        message:"查不到",
                        type:"error",
                        duration:1000,
                    }) 
                }
            })
        },
        addMarker(x, y, fnum) {
            this.removeMark();
            this.locateMarkLayer = new esmap.ESLayer(esmap.ESLayerType.TEXT_MARKER);
            var floor = this.building.getFloor(fnum)
            var im = new esmap.ESTextMarker({
                x: x,
                y: y,
                image: '/static/esmap/Case/image/user.png',
                size: 64,
                id: 1,
                height:2,
                name: 'myMarker'
            });

            this.locateMarkLayer.addMarker(im);
            floor.addLayer(this.locateMarkLayer);
        },
        removeMark() {
            if (!this.locateMarkLayer) return;
            this.locateMarkLayer.removeAll();
            var fnum = this.locateMarkLayer.FloorNum;
            this.building.getFloor(fnum).removeLayer(this.locateMarkLayer);
            this.locateMarkLayer = null;
        },
        handleChange() {
            listSpaceByArea({
                scAreaId:this.value[1]
            }).then(response => {
                MapApplication.parkData = response.rows;
                MapApplication.callLoadData(response.rows);
            });
        },
        getParkingArea() {
            listArea({
                pageNum: 1,
                pageSize: 1000,
            }).then(response => {
                this.options = this.transformData(response.rows)
            });
        },
        transformData(data) {
        // 按停车场ID分组
            const grouped = data.reduce((acc, item) => {
                const parkingLotId = item.scParkingLotId;
                if (!acc[parkingLotId]) {
                acc[parkingLotId] = {
                    value: parkingLotId,
                    label: `停车场${parkingLotId}`,
                    children: []
                };
                }
                acc[parkingLotId].children.push({
                    value: Number(item.scAreaName.replace(/\D+/g, '')),
                    label: item.scAreaName
                });
                return acc;
            }, {});

            // 返回分组后的数组
            return Object.values(grouped);
        }
    },
    mounted() {
        this.getParkingArea()
        console.log('Component mounted');
        // 确保容器已渲染
        this.$nextTick(() => {
            const container = document.getElementById('map-container');
            console.log('Container element:', container);
            
            // 延迟⼀点时间确保DOM完全准备好
            setTimeout(() => {
                console.log('Initializing map...');
                MapApplication.initMap(this.mapID, listSpaceByArea);
                MapApplication.map.on("mapClickNode", (event) => { 
                    this.parkSpaceData.name = ""
                    this.parkSpaceData.id = ""
                    this.parkSpaceData.status = "" 
                    for (var i = 0; i < MapApplication.parkData.length; ++i) {
                        if (event.name === MapApplication.parkData[i].scSpaceName) {
                            this.parkSpaceData.name = event.name
                            this.parkSpaceData.id = MapApplication.parkData[i].scSpaceId
                            this.parkSpaceData.status = this.statusname[MapApplication.parkData[i].scSpaceStatus] 
                            this.parkSpaceData.licensePlate = MapApplication.parkData[i].scLicensePlate
                            this.parkSpaceData.userName = MapApplication.parkData[i].scUsername
                            this.parkSpaceData.phone = MapApplication.parkData[i].scPhoneNumber   
                            this.dialogParkVisible = true                
                        } else if (event.name === "车位") {
                            this.parkSpaceData.name = "消防车位"
                            this.parkSpaceData.id = "000"
                            this.parkSpaceData.status = "固定车位"   
                            this.dialogParkVisible = true 
                        }
                    }
                });
            }, 1000);
        });
    },
    beforeDestroy() {
        MapApplication.destroyMap();
    }
};
</script>

<style scoped>
.map-container-wrapper {
    position: relative;
    width: 100%;
    height: 600px;
}
#map-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #f0f0f0;
}

/* 状态标识样式 */
.status-legend {
    position: absolute;
    top: 400px;
    background-color: white;
    padding: 10px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.status-item {
    display: flex;
    align-items: center;
    margin: 5px 0;
}

.status-color {
    display: inline-block;
    width: 16px;
    height: 16px;
    border-radius: 3px;
    margin-right: 8px;
}

.status-text {
    font-size: 14px;
    color: #606266;
}
</style>